package com.hzj.utils;

import io.jsonwebtoken.*;
import lombok.Data;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.stereotype.Component;

import java.lang.ref.PhantomReference;
import java.util.Date;

@Data
@Component
@ConfigurationProperties("hzj.jwt")
public class JwtUtils {

    private long expire;
    private String secret;
    private String header;

    //生成JWT
    public String generateToken(String username){

        Date nowDate = new Date();
        Date expireDate = new Date(nowDate.getTime() + 1000 * expire);

        return Jwts.builder()
                .setHeaderParam("type" , "JWT")
                .setSubject(username)
                .setIssuedAt(nowDate)
                .setExpiration(expireDate)//7天过期
                .signWith(SignatureAlgorithm.HS512 , secret)
                .compact();
    }

    //解析JWT
    public Claims getClaimByToken(String jwt){
        try {
            return Jwts.parser()
                    .setSigningKey(secret)//解析密钥
                    .parseClaimsJwt(jwt)//解析jwt
                    .getBody();
        }catch (Exception e){
            return null;
        }

    }

    //JWT是否过期
    public boolean isTokenExpired(Claims claims){
        return claims.getExpiration().before(new Date());
    }
}
